﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DevTool.Command
{
    public class MySQLDB
    {
        public readonly String connection = ConfigHelper.GetConnctionString("MySqlConnection");

        public string GetDBName()
        {

            var result = string.Empty;
            if (!string.IsNullOrEmpty(connection))
            {
                var arr = connection.Split(";");
                var dbstr = arr.Where(w=>w.ToLower().Contains("database")).FirstOrDefault();
                if (dbstr != null)
                {
                    var dbboy=dbstr.Split("=");
                    if (dbboy.Length>1)
                    {
                        result = dbboy[1];
                    }

                }
            }

            return result;

        }
        public DataTable GetDBTabeName(string dbname)
        {
            //查询
            DataTable dt = null;
            try
            {
                var sql = string.Format($"select table_name from information_schema.tables where table_schema ='{dbname}'");
                dt = Query(sql);
            }
            catch (Exception)
            {


            }
            return dt;

        }

        /// <summary>
        /// 获取表列名
        /// </summary>
        /// <param name="dbname"></param>
        /// <param name="tablename"></param>
        /// <returns></returns>
        public DataTable Getcolnumes(string tablename)
        {
            DataTable dt = null;
            var sql = string.Format(@" SELECT  *  FROM {0} LIMIT 1", tablename);
            if ((!string.IsNullOrEmpty(tablename)))
            {

                dt = Query(sql);
            }
            return dt;

        }
        public DataTable Query(string sql)
        {
            DataTable dt = new DataTable();
            MySqlConnection conn = new MySqlConnection(connection);
            MySqlCommand comm = new MySqlCommand(sql, conn);
            conn.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter(comm);
            adapter.Fill(dt);
            conn.Close();
            return dt;
        }
    }
}
